package org.example.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import org.example.JoinGroupRequestPacket;
import org.example.JoinGroupResponsePacket;
import org.example.im.SessionUtil;

public class JoinGroupRequestHandler extends SimpleChannelInboundHandler<JoinGroupRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, JoinGroupRequestPacket joinGroupRequestPacket) {
        System.out.println("服务端处理加入群聊的请求逻辑...收到的加入群聊参数:" + joinGroupRequestPacket);
        // 1、获取群聊id
        ChannelGroup channelGroup = SessionUtil.getGroup(joinGroupRequestPacket.getGroupId());

        // 将当前连接绑定到群组中
        channelGroup.add(ctx.channel());

        // 2、发送响应报文
        JoinGroupResponsePacket joinGroupResponsePacket = JoinGroupResponsePacket.builder()
                .success(true)
                .groupId(joinGroupRequestPacket.getGroupId())
                .build();

        //ctx.channel().writeAndFlush(joinGroupResponsePacket);
        // 此处可以通知群里所有人
        channelGroup.writeAndFlush(joinGroupResponsePacket);
    }
}
